package com.zzusedating.androidapp;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;

import com.zzusedating.androidapp.customlayout.SpinnerWithTitle;
import com.zzusedating.androidapp.customlayout.TextViewWithClearButton;
import com.zzusedating.androidapp.tools.ActivityCollector;
import com.zzusedating.androidapp.tools.MyApplication;
import com.zzusedating.androidapp.tools.ConstantsTools;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class RegBasicProfileActivity extends BaseActivity {
    private static final String TAG = "RegBasicProfileActivity";
    private static final int REG_SUCCESS_I = 110;
    private static final int PARA_ERROR_I = 112;
    private static final int BAD_OPERATION_I = 111;
    private static final int NETWORK_ERROR_I = 113;

    private static final String NETWORK_ERROR_ = "网路错误";
    private static final String REG_SUCCESS_ = "注册成功";
    private static final String PARA_ERROR_ = "参数错误";
    private static final String BAD_OPERATION_ = "操作不合规";


    private Button registerButton;
    private TextViewWithClearButton nameView;
    private TextViewWithClearButton phoneView;
    private SpinnerWithTitle sexView;
    private SpinnerWithTitle marryView;
    private TextView dateView;

    private View.OnClickListener registerListener;
    private View.OnClickListener datePickListener;

    private Callback regCallback;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_basic_profile);

        initCallback();
        initListener();

        registerButton = findViewById(R.id.BasicProfile_NextButton);
        nameView = findViewById(R.id.BasicProfile_UserNameTVWCBView);
        phoneView = findViewById(R.id.BasicProfile_PhoneView);
        sexView = findViewById(R.id.BasicProfile_Sex);
        marryView = findViewById(R.id.BasicProfile_SWTMarryStatus);
        dateView = findViewById(R.id.BasicProfile_datePick);
        GregorianCalendar calendar = new GregorianCalendar();
        int year = calendar.get(Calendar.YEAR), mon = calendar.get(Calendar.MONTH), day = calendar.get(Calendar.DAY_OF_MONTH);
        dateView.setText(String.format(Locale.CHINA, "%4d-%02d-%02d", year, mon, day));

        registerButton.setOnClickListener(registerListener);
        dateView.setOnClickListener(datePickListener);
    }

    public void initListener(){
        registerListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameView.getText();
                String sex = sexView.getSelection();
                String birth = (String) dateView.getText();
                String phone = phoneView.getText();
                int marryStatus = marryView.getSelectionIndex();

                if (TextUtils.isEmpty(name) || TextUtils.isEmpty(sex)
                        || TextUtils.isEmpty(birth) || TextUtils.isEmpty(phone)){
                    Toast.makeText(RegBasicProfileActivity.this, "请完善信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                Request request = new Request.Builder()
                        .get()
                        .url(String.format(ConstantsTools.BASIC_PROFILE, sex, name, birth, phone, marryStatus + 1))
                        .build();
                MyApplication.getClient().newCall(request).enqueue(regCallback);
            }
        };
        datePickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GregorianCalendar calendar = new GregorianCalendar();
                DatePickerDialog pickerDialog = new DatePickerDialog(RegBasicProfileActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        dateView.setText(String.format(Locale.CHINA, "%d-%02d-%02d", year, month, dayOfMonth));
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                pickerDialog.show();
            }
        };
    }

    public void initCallback(){
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what){
                    case NETWORK_ERROR_I:
                        Toast.makeText(RegBasicProfileActivity.this, NETWORK_ERROR_, Toast.LENGTH_SHORT).show();
                        break;
                    case BAD_OPERATION_I:
                        Toast.makeText(RegBasicProfileActivity.this, BAD_OPERATION_, Toast.LENGTH_SHORT).show();
                        break;
                    case PARA_ERROR_I:
                        Toast.makeText(RegBasicProfileActivity.this, PARA_ERROR_, Toast.LENGTH_SHORT).show();
                        break;
                    case REG_SUCCESS_I:
                        MyApplication.setBasicProfile((JSONObject) msg.obj);
                        Toast.makeText(RegBasicProfileActivity.this, REG_SUCCESS_, Toast.LENGTH_SHORT).show();
                        int sz = ActivityCollector.size();
                        startActivity(new Intent(RegBasicProfileActivity.this, MainActivity.class));
                        ActivityCollector.finishFromStart(sz);
                        break;
                }
                return true;
            }
        });

        regCallback = new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = new Message();
                message.what = NETWORK_ERROR_I;
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.code() != 200){
                    Log.e(TAG, "onResponse: response code: " + response.code());
                    return;
                }
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    if (jsonObject.getInt("status") == 1){
                        handler.sendMessage(ConstantsTools.createMessage(REG_SUCCESS_I, jsonObject.getJSONObject("data")));
                    }
                    else {
                        int code = jsonObject.getInt("code");
                        if (code == 2)
                            handler.sendMessage(ConstantsTools.createMessage(PARA_ERROR_I));
                        else if (code == -1)
                            handler.sendMessage(ConstantsTools.createMessage(BAD_OPERATION_I));
                        else
                            handler.sendMessage(ConstantsTools.createMessage());
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
